import Subject from "./subject";

export default class Network extends Subject {
    _onMessageHandle:any = null;

    constructor() {
        super();
        this._onMessageHandle = ((e) => {
            if (e) {
                if (e.data && typeof e.data === "string") {
                    return this.getMessage(JSON.parse(e.data));
                } else {
                    return console.log("message有误！");
                }
            }
        }).bind(this);

        window.addEventListener("message", this._onMessageHandle );
    }
    dispose(){
        window.removeEventListener( "message", this._onMessageHandle );
    }

    sendMessage(handleData) {
        if (window !== window.parent) {
            window.parent.postMessage(JSON.stringify({
                method: "onFileMessage",
                handleData: handleData
            }), '*');
        }
    }
    getMessage(data) {
        this.emit("getMessage", data);
    }
};